<template>
  <div class="drawer-box">
    <el-drawer v-model="showApplyWork">
      <!--    start header-->
      <template #header>
        <div class="drawer-header">
          <title-view title="申请开工" />
        </div>
      </template>
      <!--    end header-->
      <!--    start drawer-content-->
      <div class="drawer-content" v-loading="isLoading">
        <!--        start left-content-->
        <div class="left-content">
          <div class="work-information">
            <div class="base-info">
              <div class="base-info__item">
                <span class="label">业务类型</span>
                <div class="val">{{ detailInfo.portraitName }}</div>
              </div>
              <div class="base-info__item">
                <span class="label">房屋面积</span>
                <div class="val">{{ detailInfo.area }}</div>
              </div>
              <div class="base-info__item" v-if="detailInfo.contractDuration?.length">
                <span class="label">其他场景</span>
                <div class="val">{{ otherInfoString }}</div>
              </div>
              <div class="base-info__item">
                <span class="label">施工日</span>
                <div class="val">{{ detailInfo.workType == 1 ? "工作日" : detailInfo.workType == 2 ? "自然日" : "" }}</div>
              </div>
            </div>
            <div class="contract-situation">
              <div class="title">合同准备情况<span v-if="isShowContractTips">（当前合同未完签约，无法申请开工）</span></div>
              <div class="material-list">
                <!-- 1 完成合同，2 未完成合同-->
                <div class="material-item" v-for="contractItem in detailInfo.contracts">
                  <div class="material-item__text" :class="{ 'material-item--disabled': contractItem.contractStatus === 2 }">
                    {{ contractItem.contractName }}
                  </div>
                  <svg-icon v-if="contractItem.contractStatus === 1" iconClass="gray-select" style="font-size: 14px" />
                </div>
                <div class="no-data" v-if="detailInfo.contracts?.length == 0">暂无数据</div>
              </div>
            </div>
            <div class="information-situation" v-if="detailInfo.contractDatas?.length">
              <div class="title">资料准备情况<span v-if="isShowMaterialTips">（当前资料准备不全，强制开工需要审批）</span></div>
              <div class="material-list">
                <div class="material-item" v-for="materialItem in detailInfo.contractDatas">
                  <div class="material-item__text" :class="{ 'material-item--disabled': materialItem.dataStatus === 2 }">
                    {{ materialItem.dataName }}
                  </div>
                  <svg-icon
                    v-if="materialItem.dataStatus === 1"
                    iconClass="gray-select"
                    style="font-size: 14px; flex-shrink: 0"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        <!--        end left-content-->
        <!--        start right-content-->
        <div class="right-content">
          <div style="flex-grow: 1">
            <el-form ref="formRef" :model="formData" :rules="addFormRules">
              <el-form-item label="预计开工仪式时间" prop="startPlainDate">
                <el-date-picker
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  v-model="formData.startPlainDate"
                  type="date"
                  placeholder="请选择时间"
                  style="width: 100%"
                />
                <span class="advance-tips" v-if="detailInfo.advanceDays > 0"
                  >开工时间必须{{ detailInfo.advanceDays }}天后，若提前开工需要审批</span
                >
              </el-form-item>
              <el-form-item> <el-checkbox v-model="formData.star" label="设置为工程需重点关注客户" size="large" /></el-form-item>
              <el-form-item v-if="formData.star" prop="remark" style="margin-top: -10px">
                <el-input
                  v-model="formData.remark"
                  style="width: 100%"
                  maxlength="200"
                  :autosize="{ minRows: 3 }"
                  show-word-limit
                  type="textarea"
                  placeholder="请输入重点关注事项"
                />
              </el-form-item>
              <el-form-item label="其他备注说明">
                <el-input
                  v-model="formData.otherRemark"
                  style="width: 100%"
                  :autosize="{ minRows: 3 }"
                  show-word-limit
                  type="textarea"
                  maxlength="200"
                  placeholder="请输入其他备注说明"
                />
              </el-form-item>
            </el-form>
            <work-purchase v-model="purchaseList" />
          </div>
          <div class="button-action">
            <el-button color="#F2F3F5" @click="handelCancel">取消</el-button>
            <el-button color="#007DFF" @click="handelConfirm">确认</el-button>
          </div>
        </div>
        <!--        end right-content-->
      </div>
      <!--    end drawer-content-->
    </el-drawer>
  </div>
</template>

<script setup>
import { computed, getCurrentInstance, ref } from "vue";
import { applyWorkDetail, applyWorkSubmit } from "@/apis/clientManager";
import WorkPurchase from "@/components/WorkPurchase/index.vue";
const { proxy } = getCurrentInstance();
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  customerId: {
    type: String,
    default: ""
  }
});
const customerId = props.customerId;
const emit = defineEmits(["update:modelValue", "workApplySave"]);
const showApplyWork = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

//详情
const purchaseList = ref([]);
const detailInfo = ref({});
const getDetail = async () => {
  isLoading.value = true;
  const { data } = await applyWorkDetail(customerId);
  detailInfo.value = data ?? {};
  purchaseList.value = data?.stageTaskSettings ?? [];
  isLoading.value = false;
};
const otherInfoString = computed(() => {
  const contractDuration = detailInfo.value.contractDuration ?? [];
  if (contractDuration.length) {
    const otherNames = contractDuration.map(item => item.durationName);
    return otherNames.join("/");
  }
});
const isShowContractTips = computed(() => {
  const contracts = detailInfo.value.contracts ?? [];
  if (contracts.length) {
    const filterNotComplete = contracts.filter(item => item.contractStatus === 2);
    return filterNotComplete.length > 0;
  } else {
    return true;
  }
});
const isShowMaterialTips = computed(() => {
  const contractDatas = detailInfo.value.contractDatas ?? [];
  if (contractDatas.length) {
    const filterNotComplete = detailInfo.value.contractDatas.filter(item => item.dataStatus === 2);
    return filterNotComplete.length > 0;
  }
});

//表单
const initFormData = {
  customerId,
  startPlainDate: "",
  star: false,
  remark: "",
  otherRemark: ""
};
const formData = ref({ ...initFormData });
const isLoading = ref(false);
const addFormRules = {
  startPlainDate: { required: true, message: "请选择预计开工仪式时间", trigger: "change" },
  remark: { required: true, message: "请输入重点关注事项", trigger: "blur" }
};

//按钮操作
const handelConfirm = () => {
  // if (isShowContractTips.value) {
  //   return proxy.$modal.msgError("合同签约未完成，无法申请开工");
  // }
  proxy.$refs.formRef.validate(async val => {
    if (!val) {
      return proxy.$modal.msgError("请填写完整信息");
    }
    isLoading.value = true;
    let filterPurchaseList = [];
    if (purchaseList.value.length) {
      filterPurchaseList = purchaseList.value.filter(item => item.isCustomerBuy == 1);
    }
    formData.value.customerMaterialSelfBuyRecords = filterPurchaseList;
    try {
      const res = await applyWorkSubmit(formData.value);
      proxy.$modal.msgSuccess(res?.msg ?? "操作成功");
      setTimeout(() => {
        isLoading.value = false;
        showApplyWork.value = false;
        emit("workApplySave");
      }, 1000);
    } catch (err) {
      isLoading.value = false;
    }
  });
};
const handelCancel = () => {
  formData.value = { ...initFormData };
  showApplyWork.value = false;
};

getDetail();
</script>

<style scoped lang="scss">
@use "index.scss";
</style>
